package com.gitee.jmash.websocket.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.microprofile.jwt.JsonWebToken;
import com.gitee.jmash.common.grpc.GrpcMetadata;
import com.gitee.jmash.common.security.DefaultJmashPrincipal;
import com.gitee.jmash.common.security.JmashPrincipal;
import io.smallrye.jwt.auth.principal.JWTParser;
import jakarta.enterprise.inject.spi.CDI;

public class TokenUtil {

  private static Log log = LogFactory.getLog(TokenUtil.class);

  public static JWTParser getJWTParser() {
    return CDI.current().select(JWTParser.class).get();
  }

  public static JmashPrincipal parseJwt(String authorization) {
    String accessToken = authorization;
    if (authorization.startsWith(GrpcMetadata.BEARER)) {
      accessToken = authorization.substring(GrpcMetadata.BEARER.length() + 1).trim();
    }
    JsonWebToken webToken = null;
    try {
      webToken = getJWTParser().parse(accessToken);
      return DefaultJmashPrincipal.create(webToken);
    } catch (Exception ex) {
      log.error("JWT ERROR 401 Error Authorization :" + ex.getMessage());
    }
    return null;
  }

}
